//
//  YDClientManager.swift
//  weibo
//
//  Created by 孙亚东 on 16/6/24.
//  Copyright © 2016年 Sunyadong. All rights reserved.
//

import UIKit
import AFNetworking

//定义一个meiju

enum requestType: String {

    case GET = "GET"
    case POST = "POST"



}

class YDClientManager: AFHTTPSessionManager {

    //创建单例对象
    static let shareManager: YDClientManager = {
    
    
        let manager: YDClientManager = YDClientManager()
        
        
        
        return manager
        
    
    
    
    }()
    
    private init(){

        super.init(baseURL: nil, sessionConfiguration: nil)
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    func sendRequest(type: requestType,URLString: String, parameters: AnyObject?, progress downloadProgress: ((NSProgress) -> Void)?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: ((NSURLSessionDataTask?, NSError) -> Void)?){
        
        
        if type == .GET {
        
        
        self.GET(URLString, parameters: parameters, progress: downloadProgress, success: success, failure: failure)
            


        
        }else if type == .POST {
        
            
        
        self.POST(URLString, parameters: parameters, progress: downloadProgress, success: success, failure: failure)
        
        
        }
        
        
    }
    
    //由于好多参数都不能用，所以进行封装 (1),去掉progress
    func sendRequest(type: requestType,URLString: String, parameters: AnyObject?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: ((NSURLSessionDataTask?, NSError) -> Void)?){
        
        
        self.sendRequest(type, URLString: URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        
        
    }
    
    //去掉success和failure 的参数
    ///  抽取的最终方法,没有进度,没有urlSessionDataTask
    ///
    ///  - parameter type:       网络请求方法
    ///  - parameter URLString:  请求地址
    ///  - parameter parameters: 请求参数
    ///  - parameter success:    成功回调,返回JSON
    ///  - parameter failure:    失败回调,返回错误信息
    /// 需要通过方法重载对 返回成功的回调,以及 失败的回调 返回参数进行减少
    func sendRequest(type: requestType,URLString: String, parameters: AnyObject?, success: AnyObject? -> Void, failure: NSError -> Void ){
        
        
        let getSuccess = { (task: NSURLSessionDataTask, Json: AnyObject?) -> Void in
            
            
            success(Json)
            
            
            }
        
        
        
        let getFailure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            
            
            
            
            failure(error)
        
        
        }
        
        
    self.sendRequest(type, URLString: URLString, parameters: parameters, progress: nil, success: getSuccess, failure: getFailure)
        
        
        
        
    }
    
    
    
    

    
    
    

    
    
}
